package book;

import constant.Constant;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 32309
 * Date: 2025-07-17
 * Time: 21:22
 */
public class Library {
    private Book[] books;
    private AnalyzingBook analyzingBook = new AnalyzingBook();
    private int bookCount;
    private static Library library;
    Scanner scanner = new Scanner(System.in);

    public int getBookCount() {
        return bookCount;
    }

    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }

    public static Library getLibrary() {
        if (library == null) {
            return new Library();
        }
        return library;
    }
    private Library() {
        loadAllBook();
    }

    /**
     * 读取书籍
     */
    public void loadAllBook() {
        Book[] allBook = analyzingBook.loadBook(Constant.ALL_BOOK);
        books = new Book[Constant.CAPACITY];
        if (allBook == null) {
            bookCount = 0;
        }else {
            bookCount = allBook.length;
            if (bookCount > books.length) {
                books = new Book[bookCount];
            }
            for (int i = 0; i < bookCount; i++) {
                books[i] = allBook[i];
            }
        }
    }

    public void writeBook() {
        analyzingBook.writeBook(books,Constant.ALL_BOOK);
    }

    public void addBook(Book newBook) {
        if (bookCount >= books.length) {
            grow();
        }
        if (bookCount == 0) {
            newBook.setBookId(1);
        }else {
            newBook.setBookId(bookCount+1);
        }
        books[bookCount++] = newBook;
        writeBook();
        System.out.println("图书 "+newBook.getTitle()+" 上架成功！");
    }

    private void grow() {
        books = Arrays.copyOf(books,books.length * 2);
    }

    public void displayBooks() {
        loadAllBook();
        System.out.println("当前图书馆当中所有的图书: ");
        if (bookCount == 0) {
            System.out.println("当前没有任何图书！！！");
            return;
        }
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }

    public void updateBook(Book book) {
        //先找到该书是哪个下标
        int index = searchByIdReturnIndex(book.getBookId());
        books[index] = book;
        System.out.println("图书："  + book.getTitle() +" 更新成功！");
        //⼀定要进⾏存储
        writeBook();
    }

    private int searchByIdReturnIndex(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if (books[i].getBookId() == bookId) {
                return i;
            }
        }
        return -1;
    }

    public Book searchById(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if (books[i].getBookId() == bookId) {
                return books[i];
            }
        }
        return null;
    }

    public void removeBook(Book book) {
        loadAllBook();
        int index = searchByIdReturnIndex(book.getBookId());
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i + 1];
        }
        books[bookCount - 1] = null;
        bookCount--;
        writeBook();
    }

    // 所有书籍的情况
    public void borrowCount() {
        loadAllBook();
        if (bookCount == 0) {
            System.out.println("没有书籍！");
            return;
        }
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书名:"+book.getTitle()+ " 借阅次数："+book.getBorrowCount());
        }
    }

    // 最受欢迎前k本书
    public void generateBook(int k) {
        loadAllBook();
        Book[] tmp = new Book[getBookCount()];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }
        Arrays.sort(tmp);
        for (int i = 0; i < k; i++) {
            Book book = tmp[i];
            System.out.println(" 书名："+ book.getTitle()+" 作者："+ book.getTitle()+" 借阅次数："+book.getBorrowCount());
        }
    }

    // 打印所有借阅书籍的情况
    public void disBorrowedStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            if (books[i].isBorrowed()) {
                System.out.println(books[i]);
            }
        }
    }

    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = book.isBorrowed() ? "已借出" : "在馆";
            System.out.println("书名："+book.getTitle()+" ⽬前状态："+status);
        }
    }

    public void checkAndRemoveOldBooks() {
        loadAllBook();
        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        // 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        boolean flag = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();
            // 计算两个⽇期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate,
                    currentDate);
            if (yearsBetween > 1) {
                flag = true;
                if (book.isBorrowed()) {
                    System.out.println("对不起 " + book.getTitle() +  " 正在被借阅，");
                    return;
                }
                System.out.print("图书 " + book.getTitle() + " 已经上架超过⼀年，是否 移除？ (Yes/NO)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("yes")) {
                    removeBook(book);
                }
            }
        }
        if (flag) {
            return;
        }
        System.out.println("没有上架超过⼀年的图书！");
    }

    public void borrowBook(int bookId) {
        loadAllBook();
        Book book = searchById(bookId);
        book.setBorrowed(true);
        book.incrementBorrowed();
        writeBook();
    }

    public void returnBook(int bookId) {
        loadAllBook();
        Book book = searchById(bookId);
        book.setBorrowed(false);
        writeBook();
    }

    public void searchBook() {
        loadAllBook();
        System.out.println("请输⼊你要查找的图书的名称：");
        String title = scanner.nextLine();
        boolean flag = true;
        for (int i = 0; i < bookCount; i++) {
            if (books[i].getTitle().equalsIgnoreCase(title)) {
                System.out.println("找到了你要查找的书，书的详细信息如下：");
                System.out.println(books[i]);
                flag = false;
            }
        }
        if (flag) {
            System.out.println("没有你要找的这本书，你查找的书名为：" + title);
        }
    }

    public void exit() {
        System.out.println("系统已退出。。。");
        System.exit(0);
    }
}
